/**
 * [文章管理]表单[JS]
 * @returns {*}
 */
var app = function ($isCreate) {

    Vue.component('treeselect', VueTreeselect.Treeselect);
    return new Vue({
        el: '#vueContainer',
        data: {
            loadOver: false,
            detailOver: false,
            settingOver: false,
            setting: {
                pageType: 'form',    // 页面类型
                isCreate: $isCreate, // 添加状态
            },
            form: {
                uid: 0,
                cate_id: null,
                title: null,
                description: null,
                thumb: null,
                content: null,
                status: 0,
                sort: 0,
                keywords: null,
                is_origin: 0,
                reprint_url: null,
                extra_data: null,
                setting: {
                    open_seo: null,
                    seo_title: null,
                    seo_keywords: null,
                    seo_description: null,
                }
            },
            customErrMsg: {}, // 自定义错误列表
            loadingKeyWords: false, // 加载关键词中
            noSelKeywords: [], // 未选择关键词
            category: { // 分类信息
                isInit: false, // 是否已初始化
                setting: {}, // 设置
                list: [], // 分类列表
            },
            pageDialog: {
                show: false,    // 页面 - 是否展示弹出层
                url: '',        // 页面 - 弹出层连接
                loading: false, // 页面 - 弹出层加载中
                isIframe: false // 当前页面 - 是否[iframe]嵌入
            },
        },
        created: function () {
            // 初始化
            this.init();
            // 初始化下设置
            this.getSetting();
            // 初始化、获取详情
            this.initDetail();
            // 文章设置
            this.getCateSetting();
            var that = this;
            this.$nextTick(function () {
                that.loadOver = true;
                that.initMainScroll();
            });
        },
        methods: {
            /**
             * 初始化的逻辑
             */
            init: function () {

                var params = $w.getParams();
                // 是否[iframe]嵌入
                this.pageDialog.isIframe = window.self !== window.top;

                var that = this;
                // [嵌入]返回事件监听 直接走自己的返回
                if (this.pageDialog.isIframe) {
                    window.addEventListener("popstate", function($event) {
                        if (that.cancel) that.cancel(); // 返回上一页
                        window.history.forward(-1);     // 清理此页历史记录
                    }, false);
                    window.history.pushState({
                        title: "title", url: "#"
                    }, "title", "#");
                    window.history.forward(1);
                }
            },
            /**
             * 初始化滚动条
             */
            initMainScroll: function () {
                var shadowDom = this.$refs['mainScrollShadow'];
                if (!shadowDom) return false;
                this.$refs.mainScroller.wrap.onscroll = function ($event) {
                    var opacity = 0;
                    opacity = $event['srcElement']['scrollTop'] / 100;
                    opacity = opacity > 0.6 ? 0.6 : opacity
                    shadowDom['$el']['style']['box-shadow'] = '0 5px 15px 0 rgb(204, 204, 204, ' + opacity + ')';
                };
            },
            /**
             * 获取设置
             * @returns {boolean}
             */
            getSetting: function () {
                // 正在加载...
                var loadingInstance = ELEMENT.Loading.service({
                    fullscreen: false,
                    text: '加载中...',
                    customClass: 'z-index-top'
                });
                var that = this;

                // 获取各模块的值
                $w.request({
                    url: $w.getApiUrl('news.setting'),
                    type: 'get',
                    data: {
                        type: 'form' // 表单页
                    },
                    dataType: 'json',
                    afterCallback: function () {
                        that.$nextTick(function () {
                            // 隐藏正在加载
                            loadingInstance.close();
                            // 设置加载完毕
                            that.settingOver = true;
                        });
                    },
                    callback: function (event) {

                        // 失败的返回|提示
                        if (parseInt(event.no) !== 200) {

                            return that.$message({
                                showClose: true,
                                type: 'error',
                                message: event.msg ? event.msg : '操作失败，请稍后尝试'
                            });
                        }

                        // 挨个赋值[setting]中
                        for (var i in event.data) {
                            if (!event.data.hasOwnProperty(i)) continue;
                            that.$set(that.setting, i, event.data[i]);

                            // 改变键值
                            if (i.indexOf('_list') !== -1) {
                                that.setting[i] = $w.array_index(event.data[i], 'key');
                            }

                            // 默认值
                            if (i.indexOf('default_') !== -1 && that.setting.isCreate) {
                                that.form[i.replace('default_', '')] = that.setting[i];
                            }
                        }

                        // 是否开启SEO 默认值
                        that.form.setting.open_seo = that.setting.default_open_seo + '';
                    }
                });
            },
            /**
             * 获取下详细信息
             */
            initDetail: function () {

                // 正在加载。。
                var loadingInstance = ELEMENT.Loading.service({
                    fullscreen: false,
                    text: '获取中...',
                    customClass: 'z-index-top'
                });
                var that = this;

                // 是新建
                if ($isCreate) {

                    this.detailOver = true; // 详情加载完毕
                    return this.$nextTick(function () {
                        loadingInstance.close(); // 隐藏正在加载
                    });
                }

                // 获取各模块的值
                $w.request({
                    url: $w.getApiUrl('news.detail'),
                    type: 'get',
                    data: {id: $w.getParams('id')},
                    dataType: "json",
                    afterCallback: function (event) {
                        that.$nextTick(function () {
                            // 详情加载完毕
                            that.detailOver = true;
                            // 隐藏正在加载
                            loadingInstance.close();
                            setTimeout(function () {
                                // 加载下关键词
                                that.reloadKeyword(event.data.content);
                            }, 1);
                        });
                    },
                    callback: function (event) {

                        // 失败的返回|提示
                        if (parseInt(event.no) !== 200) {

                            return that.$message({
                                showClose: true,
                                type: 'error',
                                message: event.msg ? event.msg : '操作失败，请稍后尝试'
                            });
                        }

                        that.form = event.data;
                        that.$nextTick(function () {
                            // 初始化编辑器
                            that.$refs['html_editor'].editorSetContent(event.data.content);
                        });
                    }
                });
            },
            /**
             * 获取设置
             * @returns {boolean}
             */
            getCateSetting: function () {
                // 正在加载...
                var loadingInstance = ELEMENT.Loading.service({
                    fullscreen: false,
                    text: '加载中...',
                    customClass: 'z-index-top'
                });
                var that = this;

                // 获取各模块的值
                $w.request({
                    url: $w.getApiUrl('newsCategory.setting'),
                    type: 'get',
                    data: {
                        type: 'form' // 表单页
                    },
                    dataType: 'json',
                    afterCallback: function () {
                        that.$nextTick(function () {
                            // 隐藏正在加载
                            loadingInstance.close();
                        });
                    },
                    callback: function (event) {

                        // 失败的返回|提示
                        if (parseInt(event.no) !== 200) {

                            return that.$message({
                                showClose: true,
                                type: 'error',
                                message: event.msg ? event.msg : '操作失败，请稍后尝试'
                            });
                        }

                        // 挨个赋值[setting]中
                        for (var i in event.data) {
                            if (!event.data.hasOwnProperty(i)) continue;
                            that.$set(that.category.setting, i, event.data[i]);

                            // 改变键值
                            if (i.indexOf('_list') !== -1) {
                                that.category.setting[i] = $w.array_index(event.data[i], 'key');
                            }
                        }

                        // 加载分类
                        that.loadCategory('INIT');
                    }
                });
            },
            /**
             * 加载分类列表
             * @param $option
             */
            loadCategory: function ($option) {

                // 正在加载...
                var loadingInstance = ELEMENT.Loading.service({
                    fullscreen: false,
                    text: '加载中...',
                    customClass: 'z-index-top'
                });
                var that = this;

                var parentId = 0;
                if ($option.parentNode && $option.parentNode.id) {
                    parentId = $option.parentNode.id;
                }

                // 获取各模块的值
                $w.request({
                    url: $w.getApiUrl('newsCategory.list'),
                    type: 'get',
                    data: {
                        search: {
                            parent_id: parentId,
                            status: this.category.setting.status_list.open.value
                        },
                        option: {
                            load_child: true,
                            remove_ids: $w.getParams('id'),
                            child_no_del: true
                        }
                    },
                    dataType: 'json',
                    afterCallback: function () {
                        that.$nextTick(function () {
                            // 隐藏正在加载
                            loadingInstance.close();
                        });
                    },
                    callback: function (event) {

                        // 失败的返回|提示
                        if (parseInt(event.no) !== 200) {

                            return that.$message({
                                showClose: true,
                                type: 'error',
                                message: event.msg ? event.msg : '操作失败，请稍后尝试'
                            });
                        }

                        var i;
                        var stage = {};
                        switch ($option.action || $option) {
                            case 'INIT':

                                that.category.list = [];
                                for (i in event.data.list) {
                                    if (!event.data.list.hasOwnProperty(i)) continue;

                                    if ($w.isEmpty(event.data.list[i]['children'])) {
                                        that.$delete(event.data.list[i], 'children');
                                    }
                                    that.category.list.push(event.data.list[i]);
                                }
                                break;
                            case 'LOAD_CHILDREN_OPTIONS':

                                $option.parentNode.children = [];
                                for (i in event.data.list) {
                                    if (!event.data.list.hasOwnProperty(i)) continue;
                                    stage = {
                                        id: event.data.list[i]['id'],
                                        label: event.data.list[i]['name'],
                                        isDisabled: parseInt(event.data.list[i]['level']) === 3,
                                        childrenStates: {isLoading: false},
                                        hadChild: event.data.list[i]['had_children']
                                    };
                                    if (stage['hadChild'] && !stage.isDisabled) {
                                        stage['children'] = null;
                                    }
                                    $option.parentNode.children.push(stage);
                                }
                                $option.callback();
                        }

                        that.$nextTick(function () {
                            // 隐藏正在加载
                            loadingInstance.close();
                            // ☆ 未初始化 ☆
                            var id = that.form.cate_id;
                            if (!that.category.isInit && id) {
                                var node = that.$refs['selectCate'].getNode(id);
                                // 加载特定数据 子集
                                if (node.hadChild) that.$refs['selectCate'].loadChildrenOptions(node);
                                // 打开
                                if (node.hadChild) that.$refs['selectCate'].toggleExpanded(node);
                                // 初始化加载完毕
                                that.category.isInit = true;
                            } else if (!id) {
                                that.form.cate_id = null;
                            }
                        });
                    }
                });
            },
            /**
             * 分类值改变
             * @param $node
             * @param $instanceId
             */
            changeCategory: function ($node, $instanceId) {

                var that = this;
                this.$confirm('分类改变, 是否同步额外数据?', '提示', {
                    confirmButtonText: '同步',
                    cancelButtonText: '不同步',
                    type: 'warning'
                }).then(function () {
                    // 分类数据
                    if (!$node.extra_article) return that.$set(that.form, 'extra_data', {});
                    // 文章数据
                    that.$set(that.form, 'extra_data', {});
                    // *** 循环分类额外数据 添加新的 ***
                    var newsHadKey = $w.array_keys(that.form.extra_data);
                    for (var i in $node.extra_article) {
                        if (!$node.extra_article.hasOwnProperty(i)) continue;
                        if (newsHadKey && $w.in_array($node.extra_article[i]['name'], newsHadKey)) {
                            continue;
                        }
                        that.$set(that.form.extra_data, $node.extra_article[i]['name'], {
                            text: $node.extra_article[i]['text'],
                            value: $node.extra_article[i]['value']
                        });
                    }

                    // *** 循环文章数据 ***
                    var cateHadKey = $w.array_values($w.array_column(
                        $node.extra_article, 'name'
                    ));
                    for (var x in that.form.extra_data) {
                        if (!that.form.extra_data.hasOwnProperty(x)) continue;
                        if (cateHadKey && !$w.in_array(x, cateHadKey)) {
                            that.$delete(that.form.extra_data, x);
                        }
                    }
                });
            },
            /**
             * 返回上一页
             * @param $reloadList 需要加载列表
             */
            cancel: function ($reloadList) {

                // 需要重新加载下列表 && [iframe]引入的
                if ($reloadList && this.pageDialog.isIframe && window.parent.instance.getList) {
                    window.parent.instance.getList();
                }

                // 显示脚部 - 当前页面返回
                if (!this.pageDialog.isIframe) {

                } else {
                    window.parent.instance.pageDialog.show = false;
                }
            },
            /**
             * 去首页
             */
            goToIndex: function () {
                // 父级
                var parent = window.parent.top;
                if (!parent) return false;

                // 父级[vue]对象
                var vueInstance = parent.instance;
                if (!parent || !(typeof vueInstance === 'object')) return false;

                // 键值
                var key = vueInstance.tab.indexKey;
                // 操作点击
                $(parent.document).find('#tab-' + key).click();
            },
            /**
             * 添加|更新
             */
            submit: function () {

                // 强制关闭下全部弹出层
                this.$message.closeAll();
                // 清空错误信息
                this.$refs['ruleForm'].clearValidate();

                var that = this;
                // 清空错误信息
                this.$set(that, 'customErrMsg', {});
                this.$refs['ruleForm'].validate(function (valid, msg) {

                    // 验证不过 - 滚动到错误字段
                    if (!valid) {
                        var first = $w.array_first_key(msg);
                        return $w.scrollToFormItem(false, first);
                    }

                    // 连接
                    var url = that.setting.isCreate ?
                        $w.getApiUrl('news.create') :
                        $w.getApiUrl('news.update');

                    // 正在加载。。
                    var loadingInstance = ELEMENT.Loading.service({
                        fullscreen: false,
                        text: '正在提交...',
                        customClass: 'z-index-top'
                    });

                    var form = that.form;
                    form.content = that.$refs['html_editor'].getEditorHtml();

                    $w.request({
                        url: url,
                        type: 'POST',
                        data: form,
                        dataType: "json",
                        afterCallback: function () {
                            that.$nextTick(function () {
                                // 隐藏正在加载
                                loadingInstance.close();
                            });
                        },
                        callback: function (event) {

                            // 失败的返回|提示
                            if (parseInt(event.no) !== 200) {

                                for (var i in event.data.column_error) {
                                    if (!event.data.column_error.hasOwnProperty(i))
                                        continue;
                                    that.$set(that.customErrMsg, i, event.data.column_error[i]);
                                }
                                // 滚动到错误字段
                                $w.scrollToFormItem();
                                return that.$message({
                                    showClose: true,
                                    type: 'error',
                                    message: event.msg ? event.msg : '操作失败，请稍后尝试'
                                });
                            }

                            // 返回上一页
                            that.cancel(true);
                        }
                    });
                });
            },
            /**
             * 重新加载关键词
             */
            reloadKeyword: function ($content) {
                // 取出纯文本
                var content = !$content ? this.$refs['html_editor'].getEditorHtml() : $content;
                // 无内容就走标题
                if (!content || content.length < 1) {
                    content = this.form.title;
                }

                if (!content || content.length < 1) {
                    return this.$message({
                        type: 'error',
                        showClose: true,
                        message: '请填写标题或详情内容'
                    });
                }
                // 正在加载。。
                this.loadingKeyWords = true;
                var that = this;

                // 获取各模块的值
                $w.request({
                    url: $w.getApiUrl('getKeywords'),
                    type: 'POST',
                    data: {content: content},
                    dataType: "json",
                    contentType: 'application/x-www-form-urlencoded',
                    afterCallback: function () {
                        that.$nextTick(function () {

                            // 隐藏正在加载
                            that.loadingKeyWords = false;
                        });
                    },
                    callback: function (event) {

                        // 失败的返回|提示
                        if (parseInt(event.no) !== 200) {

                            return that.$message({
                                showClose: true,
                                type: 'error',
                                message: event.msg ? event.msg : '操作失败，请稍后尝试'
                            });
                        }

                        that.noSelKeywords = event.data;
                    }
                });
            },
        },
        watch: {
            /**
             * 检测默认开启SEO
             * @param $value
             */
            'setting.default_ open_seo': function ($value) {
                // 无需操作
                if ($w.isEmpty($value) || !this.setting.isCreate) return false;
                // 赋值 基础
                if ($w.isEmpty(this.form.setting.open_seo)) {
                    this.form.setting.open_seo = $value.toString();
                }
            }
        },
        computed: {
            /**
             * 基础数据SEO是否开启
             * @returns {boolean}
             */
            openSeo: function () {

                if (!this.settingOver) return false;

                return +this.form.setting.open_seo === +this.setting.open_seo_list.open.value;
            },
            /**
             * 表单验证规则
             * @returns {*}
             */
            formRules: function () {
                if (!this.detailOver) return {};
                return {
                    uid: [
                        {required: true, message: '请完善作者编号', trigger: 'blur'}
                    ],
                    cate_id: [
                        {required: true, message: '请完善分类编号', trigger: 'blur'}
                    ],
                    title: [
                        {required: true, message: '请完善标题', trigger: 'blur'}
                    ],
                    description: [
                        {required: true, message: '请完善简介', trigger: 'blur'}
                    ],
                    thumb: [
                        {required: true, message: '请完善文章封面', trigger: 'blur'}
                    ],
                    status: [
                        {required: true, message: '请完善状态', trigger: 'blur'}
                    ],
                    sort: [
                        {required: true, message: '请完善排序', trigger: 'blur'},
                        {
                            validator: $w.validateNumRange, message: false, trigger: 'blur',
                            max: this.setting.max_sort, min: this.setting.min_sort
                        },
                        {type: 'number', message: '排序必须为数字值', trigger: 'blur'}
                    ],
                    keywords: [
                        {required: true, message: '请完善关键词', trigger: 'blur'}
                    ],
                    is_origin: [
                        {required: true, message: '请完善是否原创', trigger: 'blur'}
                    ],
                };
            }
        }
    });
};
